package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.mapper.UserMapper;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author 34427
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-08-21 08:59:40
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public R login(User user) {

        //判断用户是否存在
        User one = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if(one == null){
            return R.ERROR(500,"用户名不存在");
        }

        //判断密码是否正确
        if(!one.getPassword().equals(user.getPassword())){
            return R.ERROR(500,"密码错误");
        }

        //解析成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("id", one.getId()).compact();

        //将token存入redis中
        redisTemplate.opsForValue().set("id"+one.getId(),token,20, TimeUnit.MINUTES);

        one.setPassword(null);
        one.setToken(token);

        //返回
        return R.OK(one);
    }
}




